const domObserver = chrome.runtime.getURL('lib/DOMobserver.js');
const myAxios = chrome.runtime.getURL('lib/axios.min.js');
const TARGET_DOMAINS = ['sdyx2.sd.sgcc.com.cn', 'localhost', 'c.com'];
const SCRIPT_BASE_URL = 'http://192.168.161.52:18090/api/repair/v1/repair-dict/getScript';

// 域名匹配（支持端口）
function isTargetDomain(hostname) {
    const cleanHost = hostname.split(':')[0]; // 去除端口
    return TARGET_DOMAINS.some(domain => cleanHost === domain || cleanHost.endsWith(`.${domain}`));
}

// 获取远程脚本
async function safeFetch(url) {
    const response = await fetch(url);
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    return response.text();
}
// 添加消息监听
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === 'getChromeObject') {
        // 返回需要共享的chrome对象属性或方法
        sendResponse({
            status: 'success',
            data: {
                runtime: chrome.runtime,
                storage: chrome.storage
                // 可根据需要添加其他chrome API
            }
        });
    }
    return true; // 保持消息通道开放
});

// 主监听逻辑
chrome.webNavigation.onCompleted.addListener(
    async details => {
        const url = new URL(details.url);
        if (isTargetDomain(url.hostname)) {
            try {
                //const scriptUrl = `${SCRIPT_BASE_URL}?domain=${encodeURIComponent(url.hostname)}`;
                //const scriptCode = await safeFetch(scriptUrl);
                // 这里是要注入到目标页面的脚本代码
                // 支持同时加载多个 scriptUrl
                const scriptUrls = [
                    chrome.runtime.getURL('lib/globalVar.js'),
                    chrome.runtime.getURL('script/script_global.js'),
                    chrome.runtime.getURL('script/script_address.js'),
                    chrome.runtime.getURL('script/script_yujing.js'),
                    chrome.runtime.getURL('script/script_xwqy.js'),
                    chrome.runtime.getURL('script/script_upload.js')
                    // 可继续添加更多脚本
                ];
                const scriptCodes = await Promise.all(scriptUrls.map(url => safeFetch(url)));
                //注入方法html
                await chrome.scripting.executeScript({
                    target: { tabId: details.tabId },
                    func: (domObserver, scriptCodes, myAxios) => {
                        // 2. 加载 axios
                        const loadAxios = () => {
                            return new Promise(resolve => {
                                const script = document.createElement('script');
                                script.src = myAxios;
                                script.onload = () => {
                                    console.log('axios 加载完成');
                                    resolve();
                                };
                                script.onerror = (e) => console.error('axios 加载失败', e);
                                document.head.appendChild(script);
                            });
                        };

                        // 3. 加载 DOMObserver
                        const loadObserver = () => {
                            return new Promise(resolve => {
                                const script = document.createElement('script');
                                script.src = domObserver;
                                script.onload = () => {
                                    console.log('DOMObserver 加载完成');
                                    resolve();
                                };
                                script.onerror = (e) => console.error('DOMObserver 加载失败', e);
                                document.head.appendChild(script);
                            });
                        };

                        // 4. 并行加载 + 确保顺序执行
                        Promise.all([loadAxios(), loadObserver()])
                            .then(() => {
                                // 5. 依次注入所有业务代码
                                scriptCodes.forEach(code => {
                                    const script = document.createElement('script');
                                    script.textContent = code;
                                    document.head.appendChild(script);
                                    script.remove();
                                });
                            });
                    },
                    args: [domObserver, scriptCodes, myAxios],
                    world: 'MAIN' // 使用 MAIN 确保能访问页面变量
                });

            } catch (error) {
                console.error(`[失败] ${url.hostname} 错误:`, error);
            }
        }
    },
    {
        url: [{ hostSuffix: 'sdyx2.sd.sgcc.com.cn' }, { hostSuffix: 'localhost' }, { hostSuffix: 'c.com' }]
    }
);
